package mao.leetcode.others.leetcode145;


import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node1.right = node2;
       node2.left = node3;
}

    public List<Integer> postorderTraversal_1(TreeNode root) {
        Stack<TreeNode> s = new Stack<>();
        List<Integer> res = new LinkedList<>();
        if (root == null) return res;
        s.push(root);
        while (!s.isEmpty()){
            TreeNode node = s.pop();
            res.add(0,node.val);
            if (node.left != null) s.push(node.left);
            if (node.right != null) s.push(node.right);
        }
        return res;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        TreeNode cur = root;
        TreeNode predecessor;
        while (cur != null){
            if (cur.right != null){
                predecessor = cur.right;
                while (predecessor.left != null && predecessor.left != cur)
                    predecessor=predecessor.left;
                if (predecessor.left == null){
                    res.add(0,cur.val);
                    predecessor.left = cur;
                    cur = cur.right;
                }else {
                    predecessor.left = null;
                    cur=cur.left;
                }
            }else {
                res.add(0,cur.val);
                cur = cur.left;
            }
        }
        return res;
    }

    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
}
